﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace JMT.Data.Serializer
{
    public class JModelSerializer
    {
        public void Serialize(XContainer pXNode, JModel jModel)
        {
            XElement xElement = new XElement(jModel.Type);
            xElement.Add(new XAttribute("id", jModel.Id));
            xElement.Add(new XAttribute("name", jModel.Name));
            OnSerialize(xElement, jModel);

            if (jModel is IJContainer)
            {
                IJContainer jContainer = jModel as IJContainer;
                List<JModel> children = jContainer.ToList();
                foreach (var child in children)
                {
                    JModelSerializer serializer = JSerializerFactory.Get(child.Type);
                    serializer.Serialize(xElement, child);
                }
            }

            pXNode.Add(xElement);
        }

        protected virtual void OnSerialize(XElement xElement, JModel jModel)
        {
        }

        public JModel Deserialize(XElement xElement)
        {
            string typeName = xElement.Name.LocalName;
            JModel jModel = JModelFactory.Create(typeName);
            jModel.Id = new Guid(xElement.Attribute("id").Value);
            jModel.Name = xElement.Attribute("name").Value;
            OnDeserialize(xElement, jModel);

            if (jModel is JContainer)
            {
                JContainer jContainer = (jModel as JContainer);
                List<XElement> xElements = xElement.Elements().ToList();
                foreach (var xChild in xElements)
                {
                    JModelSerializer serializer = JSerializerFactory.Get(xChild.Name.LocalName);
                    jContainer.Add(serializer.Deserialize(xChild));
                }
            }
            return jModel;
        }

        protected virtual void OnDeserialize(XElement xElement, JModel jModel)
        {
        }
    }
}
